package com.web.text.split;

import com.web.text.StringUtil;
import com.web.text.html.HtmlStrUtil;

import java.util.List;

public class StringSplit {

    private final String content;

    private final int size;

    private final List<int[]> list;

    /**
     * 构造方法 需要传入内容
     *
     * @param content
     */
    public StringSplit(String content) {
        this.content = content;
        this.size = content.length();
        this.list = HtmlStrUtil.findTag(content);
    }

    /**
     * 判断当前是否在html 标签范围中
     *
     * @param index 索引
     * @return
     */
    private boolean isRange(int index) {
        return StringUtil.isRange(this.list, index);
    }


    /**
     * 分割字符串 保留完整的html
     *
     * @param count       提取长度
     * @param splitResult 回调方法
     */
    public void split(int count, SplitResult splitResult) {
        int i = 0;
        int j = 0;
        while (i < this.size) {
            boolean range = this.isRange(i);
            if (j < count) {
                splitResult.before(this.content.charAt(i));
                if (!range) {
                    j++;
                }
            } else {
                if (range) {
                    splitResult.after(this.content.charAt(i));
                }
            }
            i++;
        }
    }

    /**
     * 分割字符串 保留完整的html
     *
     * @param count 提取长度
     */
    public String split(int count) {
        final StringBuilder sb = new StringBuilder();
        final StringBuilder sb1 = new StringBuilder();
        this.split(count, new SplitResult<Character>() {
            @Override
            public void before(Character o) {
                sb.append(o);
            }

            @Override
            public void after(Character o) {
                sb1.append(o);
            }
        });
        String after = HtmlStrUtil.cleanTagByName(sb1.toString(), false, "img");
        sb.append(after);
        return sb.toString();
    }

}
